package top.kaoshanji.p1ch07a;

import org.apache.hc.core5.http.ContentType;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * 代码清单-p1ch07a-230页a：使陈旧会话失效
 * URL访问地址：/manualInvalidate
 * @author kaoshanji
 * ^_^
 * create time 2025/4/4 19:55
 */
public class ManualInvalidate extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求对象的编码
        req.setCharacterEncoding(StandardCharsets.UTF_8.name());

        // 设置响应对象的编码和内容格式
        resp.setContentType(ContentType.TEXT_HTML.toString());
        PrintWriter out = resp.getWriter();

        // 取得当前会话对象，必要可生成一个
        HttpSession session = req.getSession();

        // 如果超过一天或一小时以上未激活，使会话无效
        if (!session.isNew()) { // 跳过新会话
            Date dayAgo = new Date(System.currentTimeMillis() - 24*60*60*1000);
            Date hourAgo = new Date(System.currentTimeMillis() - 60*60*1000);
            Date created = new Date(session.getCreationTime());
            Date accessed = new Date(session.getLastAccessedTime());

            if (created.before(dayAgo) || accessed.before(hourAgo)) {
                session.invalidate();
                session = req.getSession(); // 取得新的会话
            }

        }

        // 继续执行...

    }

}
